<?php
/**
 * Created by PhpStorm.
 * User: wangjun
 * Date: 2016-10-28
 * Time: 11:33
 */


/**
 * excel类,解析excel
 * @param string $filePath
 * @param int $sheet
 * @return array|void
 * @throws \PHPExcel_Exception
 * @throws \PHPExcel_Reader_Exception
 */
 function format_excel2array($filePath='',$sheet=0)
 {
     vendor('Classes.PHPExcel');
     if (empty($filePath) or !file_exists($filePath)) {
         die('file not exists');
     }
     $PHPReader = new \PHPExcel_Reader_Excel2007();        //建立reader对象
     if (!$PHPReader->canRead($filePath)) {
         $PHPReader = new \PHPExcel_Reader_Excel5();
         if (!$PHPReader->canRead($filePath)) {
             echo 'no Excel';
             return;
         }
     }
     $PHPExcel = $PHPReader->load($filePath);        //建立excel对象
     $currentSheet = $PHPExcel->getSheet($sheet);        //**读取excel文件中的指定工作表*/
     $allColumn = $currentSheet->getHighestColumn();        //**取得最大的列号*/
     $allRow = $currentSheet->getHighestRow();        //**取得一共有多少行*/
     $data = array();
     for ($rowIndex = 1; $rowIndex <= $allRow; $rowIndex++) {        //循环读取每个单元格的内容。注意行从1开始，列从A开始
         for ($colIndex = 'A'; $colIndex <= $allColumn; $colIndex++) {
             $addr = $colIndex . $rowIndex;
             $cell = $currentSheet->getCell($addr)->getValue();
             if ($cell instanceof PHPExcel_RichText) { //富文本转换字符串
                 $cell = $cell->__toString();
             }
             $data[$rowIndex][$colIndex] = $cell;
         }
     }
     return $data;
 }

//CURL请求的函数http_request()
//通过https 中的get 或 post
function https_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 获取access_token
 * @return mixed
 */
function access_token()
{
    $redis = linkredis();
    $access_token = $redis->get('dpa_access_token');
    if ($access_token == false) {
        $appid = C('APPID');
        $secret = C('APPSECRET');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $access_token = https_request($url);
        $access_token = json_decode($access_token, true);
        $token = $access_token['access_token'];
        $redis->set('dpa_access_token', $token);
        $redis->expire('dpa_access_token', 7100);
        return $token;
    } else {
        return $access_token;
    }
}
/**
 * 针对php5.5及以上的版本对curl中@不支持的特别方法
 * @param $url
 * @param $strPOST
 * @return bool|mixed
 */
function http_post_media($url,$strPOST)
{
    $oCurl = curl_init ();
    curl_setopt ( $oCurl, CURLOPT_SAFE_UPLOAD, false);
    if (stripos ( $url, "https://" ) !== FALSE) {
        curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYHOST, false );
    }
    curl_setopt ( $oCurl, CURLOPT_URL, $url );
    curl_setopt ( $oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $oCurl, CURLOPT_POST, true );
    curl_setopt ( $oCurl, CURLOPT_POSTFIELDS, $strPOST );
    $sContent = curl_exec ( $oCurl );
    $aStatus = curl_getinfo ( $oCurl );
    curl_close ( $oCurl );
    if (intval ( $aStatus ["http_code"] ) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

/**
 * 获取jssdk api_ticket票据
 * @return bool|string
 */
function get_ticket(){
    $redis = linkredis();
    $api_ticket = $redis->get('dpa_api_ticket');
    if($api_ticket == false){
        $access_token = access_token();
        $jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
        $jsapi_ticket = json_decode(https_request($jsapi_ticket_url),true);
        $ticket = $jsapi_ticket['ticket'];
        $redis->set('dpa_api_ticket', $ticket);
        $redis->expire('dpa_api_ticket', 7100);
        return $ticket;
    }else{
        return $api_ticket;
    }
}

/**
 * 功能：生成二维码
 * @param string $qr_data   手机扫描后要跳转的网址
 * @param string $qr_level  默认纠错比例 分为L、M、Q、H四个等级，H代表最高纠错能力
 * @param string $qr_size   二维码图大小，1－10可选，数字越大图片尺寸越大
 * @param string $save_path 图片存储路径
 * @param string $save_prefix 图片名称前缀
 */
function createQRcode($save_path,$qr_data='PHP QR Code :)',$qr_level='H',$qr_size=10,$save_prefix='qrcode'){
    if(!isset($save_path)) return '';
    //设置生成png图片的路径
    $PNG_TEMP_DIR = & $save_path;
    //导入二维码核心程序
    vendor('PHPQRcode.class#phpqrcode');  //注意这里的大小写哦，不然会出现找不到类，PHPQRcode是文件夹名字，class#phpqrcode就代表class.phpqrcode.php文件名
    //检测并创建生成文件夹
    if (!file_exists($PNG_TEMP_DIR)){
        mkdir($PNG_TEMP_DIR);
    }
    $filename = $PNG_TEMP_DIR.'test.png';
    $errorCorrectionLevel = 'L';
    if (isset($qr_level) && in_array($qr_level, array('L','M','Q','H'))){
        $errorCorrectionLevel = & $qr_level;
    }
    $matrixPointSize = 4;
    if (isset($qr_size)){
        $matrixPointSize = & min(max((int)$qr_size, 1), 10);
    }
    if (isset($qr_data)) {
        if (trim($qr_data) == ''){
            die('data cannot be empty!');
        }
        //生成文件名 文件路径+图片名字前缀+md5(名称)+.png
        $filename = $PNG_TEMP_DIR.$save_prefix.md5($qr_data.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
        //开始生成
        QRcode::png($qr_data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    } else {
        //默认生成
        QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    }
    if(file_exists($PNG_TEMP_DIR.basename($filename)))
        return basename($filename);
    else
        return FALSE;
}

/**
 * 循环目录下的所有文件
 * @param $dirName  删除文件源文件夹
 */
function delFileUnderDir( $dirName ){
    if ( $handle = opendir( "$dirName" ) ) {
        while ( false !== ( $item = readdir( $handle ) ) ) {
            if ( $item != "." && $item != ".." ) {
                if ( is_dir( "$dirName/$item" ) ) {
                    delFileUnderDir( "$dirName/$item" );
                } else {
                    if(unlink("$dirName/$item")){
                       // echo "成功删除文件： $dirName/$item".'<br>';
                    }
                }
            }
        }
        closedir( $handle );
    }
}

/**
 * @param $location 经纬度坐标
 * @return mixed  返回省市区
 */
function location($location){
    $ak = C('AK');
    $url = "http://api.map.baidu.com/telematics/v3/reverseGeocoding?location={$location}&coord_type=gcj02&ak={$ak}&output=json";
    $weizhi = json_decode(https_request($url),true);
    return $weizhi['city'];
}

/**
 * 连接redis服务器
 * @return Redis
 */
function linkredis(){
    $redisip = C('redis_host');
    $redispasswd = C('redis_passwd');
    $redisport = C('redis_port');
    $redis = new \Redis();
    if(!$redis->connect($redisip,$redisport)){
        exit('redis数据库连接失败');
    }
    if(!$redis->auth($redispasswd)){
        exit('redis数据库认证登陆失败');
    }
    $redis->select(8);//切换到第6个库
    return $redis;
}